package com.ray.websocket;


import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import com.ray.controller.base.BaseController;
import com.ray.model.User;
import com.ray.util.Commen;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/sysmsg.ws/{satoken}")
public class SysmsgWebsocket{
	
	private static int onlineCount = 0;
    private static Map<String, SysmsgWebsocket> clients = new ConcurrentHashMap<String, SysmsgWebsocket>();
    private Session session;

    String regionuser;
    @OnOpen
    public void onOpen(Session session, @PathParam("satoken") String satoken) throws IOException {

        this.session = session;
        Object loginId = StpUtil.getLoginIdByToken(satoken);
        User user = User.dao.findById(loginId);
        if(loginId == null) {
            session.close();
            throw new SaTokenException("连接失败，无效Token：" + satoken);
        }
        if(user == null) {
            session.close();
            throw new SaTokenException("连接失败，用户信息为空：" + satoken);
        }
        // put到集合，方便后续操作
        addOnlineCount();
        this.regionuser = user.getRegion()+"_"+user.getUserid();
        clients.put(regionuser, this);

    }

    @OnClose
    public void onClose() throws IOException {
        if(clients!=null && regionuser!=null){
            clients.remove(regionuser);
            subOnlineCount();
        }
    }

    @OnMessage
    public void onMessage(Session session,String message){
        System.out.println("sid为：" + session.getId() + "，发来：" + message);
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }

    public static void sendMessage(String region,String message, String user){
        for (SysmsgWebsocket item : clients.values()) {
            if(!Commen.isEmptyy(user)){
                String[] regionuser = user.split(",");
                for (int i=0;i<regionuser.length;i++){
                    regionuser[i] = region+"_"+regionuser[i];
                }
                if(Arrays.asList(regionuser).contains(item.regionuser))
                    item.session.getAsyncRemote().sendText(message);
            }else{
                if(region.equals(item.regionuser.split("_")[0]))
                    item.session.getAsyncRemote().sendText(message);
            }

        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
    	SysmsgWebsocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
    	SysmsgWebsocket.onlineCount--;
    }

    public static synchronized Map<String, SysmsgWebsocket> getClients() {
        return clients;
    }
    
}
